package cash.cmp.personal_financial_system.utils.easyexcel.listener;

import cash.cmp.personal_financial_system.model.account.Account;
import cash.cmp.personal_financial_system.model.User;
import cash.cmp.personal_financial_system.service.impl.AccountServiceImpl;
import cash.cmp.personal_financial_system.service.impl.UserServiceImpl;
import cash.cmp.personal_financial_system.utils.shrioUtil.PwdUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Transactional(rollbackFor = Exception.class)
public class UserExcelListener extends AnalysisEventListener<User> {

    //用来记录当前记录条数
    Integer index = 0;
    private List<Account> accountList = new ArrayList<>();
    private List<User> userList = new ArrayList<>();
    private Map<String,String> accounts;
    //获取用户id
    List<Integer> idList = new ArrayList<>();
    private List<String> passwords = new ArrayList<>();
    /**
     * 每隔100条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;

    //记录未导入信息的错误
    private List<String> msgList;

    private static final String errorTitle = "未导入";

    private AccountServiceImpl accountService;

    private UserServiceImpl userService;

    public UserExcelListener(UserServiceImpl userService, AccountServiceImpl accountService, List<String> msgList, Map<String,String> accounts) {
        this.userService = userService;
        this.accountService = accountService;
        this.msgList = msgList;
        this.accounts = accounts;
    }
    @Override
    public void invoke(User user, AnalysisContext analysisContext) {
        if (vertify(user)){
            Account account = new Account();
            account.setTel(user.getTel());
            //生成随机密码
            String password = PwdUtil.genRandomPwd(18);
            accounts.put(user.getTel(),password);
            //按顺序记录密码
            passwords.add(password);
            account.setPassword(password);
            accountList.add(account);
            userList.add(user);
            System.out.println("解析到一条数据:========================"+user.toString());
        }
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if(accountList.size() >= BATCH_COUNT){
            saveData();
            // 存储完成清理datas
            accountList.clear();
            userList.clear();
            passwords.clear();
            idList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }
    @Transactional(rollbackFor = Exception.class)
    public void saveData() {
        if(accountList.size() > 0 && userList.size() > 0) {
            System.out.println("==============================" + accountList.size() + "条数据，开始存储到数据库");
            accountService.saveList(accountList);
            for(Account t : accountList){
                idList.add(t.getId());
            }
            //按顺序赋予用户id
            int index = 0;
            for (Integer i : idList){
                userList.get(index).setId(i);
                index++;
            }
            userService.saveList(userList);
        }
    }
    /**
     * 对excel文件内的bill进行校验
     */
    public Boolean vertify(User user){
        Boolean flag = true;
        index++;
        String temp = errorTitle + "第" + index + "条数据,错误为：";
        if(user.getTel() == null){
            flag = false;
            temp += "用户未输入手机号 ";
            msgList.add(temp);
            return false;
        }
        Account account = accountService.getAccount(user.getTel());
        if(account != null){
            flag = false;
            temp += "用户已存在 ";
            msgList.add(temp);
            return false;
        }
        if(flag){
            return true;
        }
        return false;
    }
}
